{% extends "后台管理/template.html" %}

{% block title %}
通道模块
{% endblock %}

{% block css %}
<style>
  .passage-category {
    margin-bottom: 20px;
  }
  .passage-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 15px;
  }
  .passage-actions {
    display: flex;
    gap: 10px;
  }
  
  /* 添加新的样式 */
  .table td {
    vertical-align: middle;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 0;
  }
  
  .table td .text-truncate {
    cursor: pointer;
  }
  
  .table-hover tbody tr:hover {
    background-color: rgba(0,0,0,.03);
  }
  
  .table td a {
    text-decoration: none;
  }
  
  .table td a:hover {
    text-decoration: underline;
  }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
  {% csrf_token %}  <!-- 添加CSRF令牌 -->
  <!-- 添加分类按钮 -->
  <div class="row mb-4">
    <div class="col">
      <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addCategoryModal">
        <i class="bi bi-plus-circle"></i> 添加分类
      </button>
    </div>
  </div>

  <!-- 分类列表 -->
  <div id="passageCategories">
    <!-- 分类内容将通过JS动态加载 -->
  </div>

  <!-- 添加分类模态框 -->
  <div class="modal fade" id="addCategoryModal" tabindex="-1">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">添加分类</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <div class="mb-3">
            <label class="form-label">分类名称</label>
            <input type="text" class="form-control" id="categoryName">
          </div>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary" onclick="addCategory()">添加</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 添加通道模态框 -->
  <div class="modal fade" id="addPassageModal" tabindex="-1">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">添加通道</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body">
          <div class="mb-3">
            <label class="form-label">通道名称</label>
            <input type="text" class="form-control" id="passageName">
          </div>
          <div class="mb-3">
            <label class="form-label">通道URL</label>
            <input type="text" class="form-control" id="passageUrl">
          </div>
          <div class="mb-3">
            <label class="form-label">通道描述</label>
            <textarea class="form-control" id="passageDescription"></textarea>
          </div>
          <div class="mb-3">
            <label class="form-label">通道图标</label>
            <input type="file" class="form-control" id="passageIcon" accept="image/*">
          </div>
          <input type="hidden" id="categoryId">
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
          <button type="button" class="btn btn-primary" onclick="addPassage()">添加</button>
        </div>
      </div>
    </div>
  </div>

  <!-- 在现有模态框后面添加删除确认模态框 -->
  <div class="modal fade" id="deleteCategoryModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header bg-danger text-white">
          <h5 class="modal-title">
            <i class="bi bi-exclamation-triangle-fill me-2"></i>
            危险操作确认
          </h5>
        </div>
        <div class="modal-body">
          <div class="text-center mb-4">
            <i class="bi bi-exclamation-triangle-fill text-danger" style="font-size: 3rem;"></i>
          </div>
          <p class="fw-bold text-danger text-center mb-3">此操作不可恢复！</p>
          <p class="mb-3">您即将删除此通道分类，请注意：</p>
          <ul class="text-danger">
            <li>该分类下的所有通道数据将被永久删除</li>
            <li>删除后数据无法恢复</li>
            <li>相关的所有记录都会被清除</li>
          </ul>
          <div class="alert alert-warning mt-3">
            <i class="bi bi-info-circle-fill me-2"></i>
            如果您不确定，请点击取消按钮
          </div>
          <input type="hidden" id="deleteCategoryId">
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
            <i class="bi bi-x-circle me-2"></i>取消
          </button>
          <button type="button" class="btn btn-danger" onclick="confirmDeleteCategory()">
            <i class="bi bi-trash me-2"></i>确认删除
          </button>
        </div>
      </div>
    </div>
  </div>

  <!-- 添加删除通道确认模态框 -->
  <div class="modal fade" id="deletePassageModal" tabindex="-1" data-bs-backdrop="static">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content">
        <div class="modal-header bg-danger text-white">
          <h5 class="modal-title">
            <i class="bi bi-exclamation-triangle-fill me-2"></i>
            删除通道确认
          </h5>
        </div>
        <div class="modal-body">
          <div class="text-center mb-4">
            <i class="bi bi-trash-fill text-danger" style="font-size: 3rem;"></i>
          </div>
          <p class="fw-bold text-danger text-center mb-3">确定要删除这个通道吗？</p>
          <div class="alert alert-warning">
            <i class="bi bi-info-circle-fill me-2"></i>
            删除后将无法恢复，请谨慎操作
          </div>
          <input type="hidden" id="deletePassageId">
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
            <i class="bi bi-x-circle me-2"></i>取消
          </button>
          <button type="button" class="btn btn-danger" onclick="confirmDeletePassage()">
            <i class="bi bi-trash me-2"></i>确认删除
          </button>
        </div>
      </div>
    </div>
  </div>
</div>
{% endblock %}

{% block js %}
<script>
  // 获取通道数据
  async function getPassageData() {
    try {
    //   请求头Content-Type要是表单的
      const response = await fetch('/api/passage/get_passage/', {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      });
      const data = await response.json();
      if (data.code === 200) {
        renderPassageCategories(data.data);
      } else {
        showToast('error', data.msg || '获取数据失败');
      }
    } catch (error) {
      showToast('error', '网络错误');
    }
  }

  // 渲染分类和通道列表
  function renderPassageCategories(categories) {
    const container = document.getElementById('passageCategories');
    container.innerHTML = categories.map(category => {
        return `
      <div class="passage-category card">
        <div class="card-header passage-header">
          <h5 class="mb-0">${category.PassageCategoryName}</h5>
          <div class="passage-actions">
            <button class="btn btn-primary btn-sm" onclick="openAddPassageModal('${category.id}')">
              <i class="bi bi-plus"></i> 添加通道
            </button>
            <button class="btn btn-danger btn-sm" onclick="deleteCategory('${category.id}')">
              <i class="bi bi-trash"></i> 删除分类
            </button>
          </div>
        </div>
        <div class="card-body">
          <div class="table-responsive">
            <table class="table table-hover">
              <thead>
                <tr>
                  <th style="width: 80px;">ID</th>
                  <th style="width: 15%;">名称</th>
                  <th style="width: 25%;">URL</th>
                  <th style="width: 30%;">描述</th>
                  <th style="width: 15%;">创建时间</th>
                  <th style="width: 100px;">操作</th>
                </tr>
              </thead>
              <tbody>
                ${(category.items || []).map(item => `
                  <tr>
                    <td>${item.id}</td>
                    <td>
                      <div class="text-truncate" style="max-width: 150px;" title="${item.name}">
                        ${item.name}
                      </div>
                    </td>
                    <td>
                      <div class="text-truncate" style="max-width: 250px;" title="${item.url}">
                        <a href="${item.url}" target="_blank" class="text-primary">
                          ${item.url}
                        </a>
                      </div>
                    </td>
                    <td>
                      <div class="text-truncate" style="max-width: 300px;" title="${item.description}">
                        ${item.description}
                      </div>
                    </td>
                    <td>
                      <div class="text-truncate" style="max-width: 150px;" title="${formatTime(item.create_time)}">
                        ${formatTime(item.create_time)}
                      </div>
                    </td>
                    <td>
                      <button class="btn btn-danger btn-sm" onclick="deletePassage(${item.id})">
                        <i class="bi bi-trash"></i> 删除
                      </button>
                    </td>
                  </tr>
                `).join('')}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    `}).join('');

    // 初始化所有工具提示
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[title]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });
  }

  // 添加格式化时间的函数
  function formatTime(timeStr) {
    if (!timeStr) return '';
    const date = new Date(timeStr);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  }

  // 打开添加通道模态框
  function openAddPassageModal(categoryId) {
    console.log('Opening modal for category ID:', categoryId); // 添加调试日志
    if (!categoryId) {
        showToast('分类ID不能为空', 'error');
        return;
    }
    document.getElementById('categoryId').value = categoryId;
    const modal = new bootstrap.Modal(document.getElementById('addPassageModal'));
    modal.show();
  }

  // 修改添加分类函数
  async function addCategory() {
    const name = document.getElementById('categoryName').value;
    if (!name) {
      showToast('请输入分类名称', 'warning');
      return;
    }

    try {
      // 获取CSRF Token
      const csrfToken = document.querySelector('input[name="csrfmiddlewaretoken"]').value;
      
      // 创建FormData对象
      const formData = new FormData();
      formData.append('name', name);
      
      // 将FormData转换为URLSearchParams
      const urlEncodedData = new URLSearchParams(formData).toString();
      
      const response = await fetch('/api/passage/create/', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',  // 修改为表单格式
          'X-CSRFToken': csrfToken
        },
        body: urlEncodedData  // 使用URL编码的表单数据
      });
      
      const data = await response.json();
      
      if (data.code === 200) {
        showToast(data.msg || '创建成功', 'success');
        document.getElementById('categoryName').value = '';
        const modal = bootstrap.Modal.getInstance(document.getElementById('addCategoryModal'));
        modal.hide();
        getPassageData();
      } else {
        showToast(data.msg || '创建失败', 'error');
      }
    } catch (error) {
      console.error('添加分类错误:', error);
      showToast('网络错误，请稍后重试', 'error');
    }
  }

  // 修改添加通道函数
  async function addPassage() {
    // 获取表单数据
    const name = document.getElementById('passageName').value;
    const url = document.getElementById('passageUrl').value;
    const description = document.getElementById('passageDescription').value;
    const category = document.getElementById('categoryId').value;
    const iconFile = document.getElementById('passageIcon').files[0];

    // 添加调试日志
    console.log('Form Data:', {
        name,
        url,
        description,
        category,
        hasIcon: !!iconFile
    });

    // 表单验证
    if (!name || !url || !description || !category || !iconFile) {
        showToast('请填写完整信息', 'warning');
        return;
    }

    try {
        const csrfToken = document.querySelector('input[name="csrfmiddlewaretoken"]').value;
        const formData = new FormData();
        formData.append('name', name);
        formData.append('url', url);
        formData.append('description', description);
        formData.append('category', category);
        formData.append('icon', iconFile);

        // 添加调试日志
        for (let pair of formData.entries()) {
            console.log(pair[0] + ': ' + pair[1]);
        }

        const response = await fetch('/api/passage/create_passage/', {
            method: 'POST',
            headers: {
                'X-CSRFToken': csrfToken
            },
            body: formData
        });
        
        const data = await response.json();
        
        if (data.code === 200) {
            showToast(data.msg || '创建成功', 'success');
            
            // 清空表单
            document.getElementById('passageName').value = '';
            document.getElementById('passageUrl').value = '';
            document.getElementById('passageDescription').value = '';
            document.getElementById('passageIcon').value = '';
            document.getElementById('categoryId').value = '';
            
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('addPassageModal'));
            modal.hide();
            
            // 重新加载数据
            getPassageData();
        } else {
            showToast(data.msg || '创建失败', 'error');
        }
    } catch (error) {
        console.error('添加通道错误:', error);
        showToast('网络错误，请稍后重试', 'error');
    }
  }

  // 修改删除分类函数
  function deleteCategory(categoryId) {
    document.getElementById('deleteCategoryId').value = categoryId;
    const modal = new bootstrap.Modal(document.getElementById('deleteCategoryModal'));
    modal.show();
  }

  // 添加确认删除的函数
  async function confirmDeleteCategory() {
    const categoryId = document.getElementById('deleteCategoryId').value;
    
    try {
        const csrfToken = document.querySelector('input[name="csrfmiddlewaretoken"]').value;
        const formData = new FormData();
        formData.append('id', categoryId);
        
        const urlEncodedData = new URLSearchParams(formData).toString();

        const response = await fetch('/api/passage/delete_passage_category/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRFToken': csrfToken
            },
            body: urlEncodedData
        });
        
        const data = await response.json();
        
        if (data.code === 200) {
            showToast(data.msg || '删除成功', 'success');
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('deleteCategoryModal'));
            modal.hide();
            // 重新加载数据
            getPassageData();
        } else {
            showToast(data.msg || '删除失败', 'error');
        }
    } catch (error) {
        console.error('删除分类错误:', error);
        showToast('网络错误，请稍后重试', 'error');
    }
  }

  // 修改删除通道函数
  function deletePassage(passageId) {
    document.getElementById('deletePassageId').value = passageId;
    const modal = new bootstrap.Modal(document.getElementById('deletePassageModal'));
    modal.show();
  }

  // 添加确认删除通道的函数
  async function confirmDeletePassage() {
    const passageId = document.getElementById('deletePassageId').value;
    
    try {
        const csrfToken = document.querySelector('input[name="csrfmiddlewaretoken"]').value;
        const formData = new FormData();
        formData.append('id', passageId);
        
        const urlEncodedData = new URLSearchParams(formData).toString();

        const response = await fetch('/api/passage/delete_passage/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'X-CSRFToken': csrfToken
            },
            body: urlEncodedData
        });
        
        const data = await response.json();
        
        if (data.code === 200) {
            showToast(data.msg || '删除成功', 'success');
            // 关闭模态框
            const modal = bootstrap.Modal.getInstance(document.getElementById('deletePassageModal'));
            modal.hide();
            // 重新加载数据
            getPassageData();
        } else {
            showToast(data.msg || '删除失败', 'error');
        }
    } catch (error) {
        console.error('删除通道错误:', error);
        showToast('网络错误，请稍后重试', 'error');
    }
  }

  // 页面加载完成后获取数据
  document.addEventListener('DOMContentLoaded', getPassageData);
</script>
{% endblock %}

{% block nav_left %}
{% include '后台管理/components/左侧导航栏.html' %}
{% endblock %}

{% block NavBar %}
{% endblock %}

{% block footer %}{% endblock %}